package com.mhl.adapter;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.mhl.campuscabinet.MyRegisterActivity;
import com.mhl.campuscabinet.ProductActivity;
import com.mhl.campuscabinet.R;
import com.mhl.client.HttpUtil;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.Product;
import com.mhl.entity.User;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

// 该类为主页瀑布流布局RecycleView的内容适配器
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
    // 所需要展示商品的实体List
    private List<Product> mProductList;
    private int itemId;
    private String itemName;
    private double itemPrice;
    private String itemDescription;
    private String itemDate;
    private int itemProvider;
    private String itemProviderName;
    private int itemStarNum;
    private int itemState;

    // private String itemUrl;
    private ArrayList<String> urls = new ArrayList<>();
    private ArrayList<Integer> tags = new ArrayList<>();
    private ArrayList<Integer> star_list = new ArrayList<>();
    private AppCompatActivity activity;
    private Handler handler;

    // 内部静态类负责对已加载的商品布局信息进行缓存
    static class ViewHolder extends RecyclerView.ViewHolder {
        View productView;
        ImageView productImage;
        TextView productName;
        TextView productPrice;

        public ViewHolder(View view) {
            super(view);
            productView = view;
            productImage = (ImageView) view.findViewById(R.id.product_image);
            productName = (TextView) view.findViewById(R.id.product_name);
            productPrice = (TextView) view.findViewById(R.id.product_price);
        }
    }

    // 构造方法，负责存储传入的商品实体列表
    public ProductAdapter(List<Product> productList, AppCompatActivity activity) {
        mProductList = productList;
        this.activity = activity;
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);

                Intent intent = new Intent(activity, ProductActivity.class);
                intent.putExtra("name", itemName);
                intent.putExtra("provider_name", itemProviderName);
                intent.putExtra("provider_id", itemProvider);
                intent.putExtra("star_number", itemStarNum);
                intent.putExtra("state", itemState);
                intent.putExtra("item_id", itemId);
                intent.putExtra("price", itemPrice);
                intent.putExtra("date", itemDate);
                intent.putExtra("description", itemDescription);
                intent.putExtra("url", urls);
                intent.putExtra("tag", tags);
                intent.putExtra("star_list", star_list);
                activity.startActivity(intent);
            }
        };
    }

    @NonNull
    @org.jetbrains.annotations.NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull @org.jetbrains.annotations.NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.product_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);

        holder.productView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Product product = mProductList.get(position);
                JSONObject jsonParam = new JSONObject();
                try {
                    jsonParam.put("id", product.getId());
                    System.out.println("商品号为 "+product.getId());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = jsonParam.toString();
                MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

                OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "merchandise/get", requestBody, new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        System.out.println(e);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                        final String data = response.body().string();
                        //处理时间
                        String allInfo = "";
                        String beforeT = "";
                        String afterT = "";
                        try {

                            int state = 1;
                            try {
                                JSONObject errcodeJson = new JSONObject(data);
                                state = errcodeJson.getInt("errcode");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            if (state != 0) {
                                Toast.makeText(activity, "Can't load detail page", Toast.LENGTH_SHORT).show();
                            }
                            System.out.println("没有问题！！！！！！！！！！！！！！");

                            JSONObject itemsJson = new JSONObject(data);
                            JSONObject itemsDetail = itemsJson.getJSONObject("data");
                            itemId = itemsDetail.getInt("id");
                            itemProvider = itemsDetail.getInt("provider_id");
                            itemProviderName = itemsDetail.getString("provider_name");
                            itemState = itemsDetail.getInt("state");
                            itemStarNum = itemsDetail.getInt("star_number");
                            itemName = itemsDetail.getString("name");
                            itemPrice = itemsDetail.getDouble("pre_price");
                            itemDescription = itemsDetail.getString("description");

                            //处理时间
                            allInfo = itemsDetail.getString("create_datetime");
                            beforeT = allInfo.substring(0,allInfo.indexOf("T"));
                            afterT = allInfo.substring(beforeT.length()+1,beforeT.length()+6);
                            allInfo = beforeT + "-" + afterT;
                            itemDate = allInfo;

                            JSONArray urlJSON = itemsDetail.getJSONArray("url_list");
                            urls.clear();
                            for (int i = 0; i < urlJSON.length(); i++) {
                                urls.add(urlJSON.getString(i));
                            }
                            JSONArray tagJSON = itemsDetail.getJSONArray("tag_id_list");
                            tags.clear();
                            for (int i = 0; i < tagJSON.length(); i++) {
                                tags.add(tagJSON.getInt(i));
                            }
                            star_list.clear();
                            JSONArray starJSON = itemsDetail.getJSONArray("star_list");
                            for (int i = 0; i < starJSON.length(); i++) {
                                star_list.add(starJSON.getInt(i));
                            }

                            handler.sendEmptyMessage(1);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

            }
        });
        // 为了方便调试把监听器禁了
        //holder.productView.setOnClickListener(null);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull ProductAdapter.ViewHolder holder, int position) {
        Product product = mProductList.get(position);
        // 使用网络上推荐的Glide
        int screenWidth = activity.getResources().getDisplayMetrics().widthPixels;
        int width = screenWidth/2 - 10;
        // TODO 为了方便调试没有通过product.getUrls().get(0)获取封面url
        Glide.with(activity).load(product.getURL()).override(width, Target.SIZE_ORIGINAL).fitCenter().into(holder.productImage);

        holder.productName.setText(product.getName());

        holder.productPrice.setText(product.getPrice() + "");
    }


    // 获取List中商品实体的个数
    @Override
    public int getItemCount() {
        return mProductList.size();
    }
//
//    @Override
//    public long getItemId(int position) {
//        return position;
//    }

}
